package com.hsq.reflection;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionQuestion01 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        m1();
        m2();
        m3();
    }

    public static void m1() {
        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 900000000; i ++) {
            cat.hi();
        }
        long end = System.currentTimeMillis();
        System.out.println("m1() = " + (end - start));
    }
    public static void m2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //加载类，返回Class类型的对象cls
        Class cls = Class.forName("com.hsq.reflection.Cat");
        //通过对象cls得到你加载的类com.hsq.reflection.Cat
        Object o = cls.newInstance();
        Method method = cls.getMethod("hi");
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 900000000; i ++) {
            method.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("m1() = " + (end - start));
    }
    public static void m3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        //加载类，返回Class类型的对象cls
        Class cls = Class.forName("com.hsq.reflection.Cat");
        //通过对象cls得到你加载的类com.hsq.reflection.Cat
        Object o = cls.newInstance();
        Method hi = cls.getMethod("hi");
        hi.setAccessible(true);//在反射调用方法时，取消访问检测，可提高速度
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 900000000; i ++) {
            hi.invoke(o);
        }
        long end = System.currentTimeMillis();
        System.out.println("m1() = " + (end - start));
    }
}
